<template>
  <el-tabs :value="this.editableTabsValue" type="card" closable style="width: 100%;height: 100%;" @tab-remove="removeTab">
    <el-tab-pane
      v-for="(item, index) in editableTabs"
      :key="index"
      :label="item.title"
      :name="item.name"
      style="width: 100%;height: 100%;">
      <iframe :src="item.url" width="100%" height="100%" frameborder="0" scrolling="no"></iframe>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
export default {
  name: "tabs",
  data() {
    return {
      BASE_URL: 'http://localhost:8080/#',
      editableTabsValue: '1',
      editableTabs: [{
        title: 'www.baidu.com',
        name: '1',
        url: 'http://localhost:8080/#/hello'
      }, {
        title: 'Tab 2',
        name: '2',
        url: '/hello'
      }],
      tabIndex: 2
    }
  },
  methods: {
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
    }
  },
  mounted() {
    let that = this;
    that.$eventBus.$on('addTab', msg => {
      for(let i = 0; i < this.editableTabs.length; i++) {
        if(msg.title === this.editableTabs[i].title) {
          this.editableTabsValue = String(i + 1);
          return;
        }
      }
      this.editableTabs.push({title: msg.title, name: String(++this.tabIndex), url: this.BASE_URL + msg.url});
      this.editableTabsValue = String(this.editableTabs.length);
    })
  }
}
</script>

<style>
  .el-tabs .el-tabs__content {
    height: 100%;
  }
</style>
